<?php
/**
 * Created by PhpStorm.
 * User: luzhaoyang
 * Date: 2017/6/21
 * Time: 14:12
 */
class Kdtsalesman_model extends Base_Model
{
    public function __construct()
    {
        parent::__construct();
        $this->load->database();
    }

    public function checkExsit($table,$ret,$where=array())
    {
        $res = $this->db->select($ret)->from($table)->where($where)->get()->row_array();
        if (empty($res)) return false;
        else return $res;
    }

    public function insertData($table,$data)
    {
        $this->db->insert($table,$data);
        return $this->db->insert_id();
    }

    public function updateData($table,$data,$where){
        return $this->db->update($table,$data,$where);
    }

    public function syncSalesman($data)
    {
        $exist = $this->checkExsit('mod_salesman','id',array('idcode'=>$data['idcode']));
        if ($exist===false){
            return $this->insertData('mod_salesman',$data);
        }else{return $this->updateData('mod_salesman',$data,array('id'=>$exist['id']));}
    }

    public function getSalesman($sls)
    {
        $res=$this->checkExsit('mod_salesman','phone',array('idcode'=>$sls));
        if ($res!==false) return $res['phone'];
        return $res;
    }

    public function getInviSalesmanNum($mobile)
    {
        $res = $this->db->select('count("id") as num')->from('mod_salesman')->where('invifrom =',$mobile)->get()->row_array();
        return $res['num'];
    }

    public function getSlsCustomerList($sls,$pageno,$pagesize)
    {
        $mobile = $this->getSalesman($sls);
        if ($mobile===false) return false;//销售员不存在

        $this->load->model('kdt_api_model');
        $res = $this->kdt_api_model->getSalesmanCustomers($mobile,$pageno,$pagesize);
        if ($res===false) return false;//有赞接口错误

        $end=0;
        $listsize = $pagesize*$pageno;
        if ($res['total_results']<$listsize||$res['total_results']==$listsize) $end=1;

        $fansidsarr = array();
        foreach ($res['customers'] as $row){
            $fansidsarr[] = $row['fans_id'];
        }

        $fansids = implode(',',$fansidsarr);
        $customers = $this->kdt_api_model->getBatchUserInfo('',$fansids,'traded_num,traded_money');
        if ($customers===false) return false;//有赞接口错误

        foreach ($res['customers'] as $index=>&$row){
            $row['nickname'] = empty($row['nickname'])?"匿名用户":$row['nickname'];
            $row['traded_num'] = $customers[$index]['traded_num'];
            $row['traded_money'] = $customers[$index]['traded_money'];
        }
        return array('list'=>$res['customers'],'end'=>$end);
    }

    public function getCoupons($sls)
    {
        $this->load->model('redis_model');
        $redis=$this->redis_model->getRedisInstance();
        $ids=$redis->sMembers('seller:'.$sls.'.coupons');
        if (!empty($ids)) {
            $res = $this->db->select('couponid,title,at_least,value')->from('kdt_coupons')->where_in('couponid',$ids)->get()->result_array();
            if (empty($res)) return false;
            foreach ($res as &$row){
                $row['at_least']/=100;
                $row['value']/=100;
            }
            return $res;
        }
        else return false;
    }
    public function getArticles($offset,$limit)
    {
        $data=$this->db->select('id,title,desc,cover,model,created')
            ->from('mod_salesman_article')
            ->where(array('status'=>1))
            ->order_by('sort','ASC')
            ->limit($limit,$offset)
            ->get()->result_array();
        foreach ($data as &$row){
            $row['created']=date('Y-m-d',$row['created']);
            $row['cover']="http://wap.nldou.com".$row['cover'];
        }
        $end = 0;
        $total = $this->db->where(array('status'=>1))->count_all_results('mod_salesman_article');
        $listsize = $limit+$offset;
        if ($total<$listsize||$total==$listsize) $end=1;

        return array('list'=>$data,'end'=>$end);
    }
    public function createArticle($model,$sls)
    {
        $this->load->model('redis_model');
        $redis=$this->redis_model->getRedisInstance();
        $artid=$redis->get('salesman.article.reverse.'.$model.$sls);
        if ($artid===false){
            //查看文章是否存在
            $res=$this->checkExsit('mod_salesman_article','id',array('model'=>$model));
            if ($res===false) return false;
            //生成随机key
            $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            $str = "";
            for ( $i = 0; $i < 6; $i++ )  {
                $str .= substr($chars, mt_rand(0, strlen($chars)-1), 1);
            }
            //生成值
            $value=array('model'=>$model,'sls'=>$sls);
            $value=igbinary_serialize($value);
            //存入redis
            $redis->set('salesman.article.'.$str,$value);
            $redis->set('salesman.article.reverse.'.$model.$sls,$str);
            $redis->sAdd('salesman.'.$sls.'.article',$model);
            return $str;
        }else{return $artid;}
    }
    public function syncSalesmanArticle()
    {
        $salesmen=$this->db->select('idcode')->from('mod_salesman')->get()->result_array();
        $models=$this->db->select('model')->from('mod_salesman_article')->get()->result_array();

        $this->load->model('redis_model');
        $redis=$this->redis_model->getRedisInstance();
        foreach ($models as $m){
            foreach ($salesmen as $s){
                $res=$redis->get('salesman.article.reverse.'.$m['model'].$s['idcode']);
                if ($res!==false) {
                    $redis->sAdd('salesman.'.$s['idcode'].'.article',$m['model']);
                    echo '*salesman '.$s['idcode'].' share '.$m['model'].PHP_EOL;
                }
            }
        }
    }
    public function showArticle($artid,$uid)
    {
        $this->load->model('redis_model');
        $redis=$this->redis_model->getRedisInstance();
        $data=$redis->get('salesman.article.'.$artid);
        //如果文章存在
        if ($data!==false){
            $data=igbinary_unserialize($data);

            $isread = $redis->getBit('salesman.article.read.'.$artid,$uid);
            //如果没有阅读
            if ($isread===0){
                //原始数据队列
                $stat = array('uid'=>$uid,'timestamp'=>time(),'sls'=>$data['sls'],'model'=>$data['model'],'randkey'=>$artid);
                $statstr = igbinary_serialize($stat);
                $redis->multi();
                //标记为已读
                $redis->setBit('salesman.article.read.'.$artid,$uid,1);
                $redis->rPush('slsartv2.read.stat',$statstr);
                $redis->exec();
            }
            //获取目前的阅读量
            $read = $redis->bitCount('salesman.article.read.'.$artid);
            $ret=array('sls'=>$data['sls'],'type'=>'show','key'=>$artid,'read'=>$read,'model'=>$data['model']);
            return $ret;
        }else{die('article does not exist');}
    }
    public function getPosts($offset,$limit)
    {
        $data=$this->db->select('id')
            ->from('mod_salesman_post')
            ->where(array('status'=>1))
            ->order_by('sort','ASC')
            ->limit($limit,$offset)
            ->get()->result_array();

        return $data;
    }
    public function getArticleStatus($sls)
    {
        $this->load->model('redis_model');
        $redis=$this->redis_model->getRedisInstance();
        $models=$redis->sMembers('salesman.'.$sls.'.article');
        //是否分享过文章
        if(!empty($models)){
            $articlenum=count($models);

            $artread=array();
            $artread['total']=0;
            foreach ($models as $m){
                $artid=$redis->get('salesman.article.reverse.'.$m.$sls);
                $artread[$m]=$redis->bitCount('salesman.article.read.'.$artid);
                $artread['total']+=(int)$artread[$m];
            }

            $artprofit=$artread['total']*10;//文章总收益（read*0.1*100）

            return array('num'=>$articlenum,'read'=>$artread,'profit'=>$artprofit);
        }else{return array('num'=>0,'read'=>array('total'=>0),'profit'=>0);}

    }
    public function getArticleTotalDemandMoney($sls)
    {
        $res=$this->db->select('SUM(money) as totalDemandMoney')->from('mod_salesman_money')
            ->where('sls =',$sls)->get()->row_array();
        return (int)$res['totalDemandMoney'];
    }
    public function getShareRemainMoney($sls)
    {
        $todaystr = date('Ymd',time());
        $this->load->model('redis_model');
        $redis = $this->redis_model->getRedisInstance();
        $redis->multi();
        $redis->get('slspostv2.scantotal.'.$sls);//海报总扫描数
        $redis->sCard('slspostv2.posts.'.$sls);//被扫描海报总数
        $redis->zScore('slspostv2.scantotal.'.$todaystr,$sls);//今日海报扫描数
        $redis->get('slsartv2.readtotal.'.$sls);//文章总阅读数
        $redis->sCard('salesman.'.$sls.'.article');//分享了文章总数
        $redis->zScore('slsartv2.readtotal.'.$todaystr,$sls);//今日文章阅读数
        $res = $redis->exec();
        $posttotalscan= $res[0]===false?0:(int)$res[0];
        $postsharenum = (int)$res[1];
        $posttodayscan= (int)$res[2];
        $arttotalread = $res[3]===false?0:(int)$res[3];
        $artsharenum  = (int)$res[4];
        $arttodayread = (int)$res[5];
        $totalMoney=($posttotalscan+$arttotalread)*10;//总收益（read*0.1*100）
        //获取已提现金额
        $totalDemandMoney=$this->getArticleTotalDemandMoney($sls);
        //获取剩余金额
        $remainMoney=$totalMoney-$totalDemandMoney;
        return array('remainmoney'=>$remainMoney/100,
            'posttotalscan'=>$posttotalscan,
            'postsharenum'=>$postsharenum,
            'posttodayscan'=>$posttodayscan,
            'arttotalread'=>$arttotalread,
            'artsharenum'=>$artsharenum,
            'arttodayread'=>$arttodayread);
    }
    public function demandArticleMoney($sls,$money)
    {
        //获取总收益
        $res=$this->getArticleStatus($sls);
        $totalMoney=$res['profit'];
        //获取已提现金额
        $totalDemandMoney=$this->getArticleTotalDemandMoney($sls);
        //获取剩余金额
        $remainMoney=$totalMoney-$totalDemandMoney;
        //剩余金额不能低于10元
        if ($remainMoney<1000) return array('status'=>2);
        //提现金额不能超过剩余金额
        if ($remainMoney<$money) return array('status'=>3);
        //提交提现申请
        $data=array('sls'=>$sls,'money'=>$money,'status'=>1,'created'=>time());
        $id=$this->insertData('mod_salesman_money',$data);
        //获取剩余提现金额
        $remaintodemand=($remainMoney-$money)/100;
        return array('status'=>1,'remainmoney'=>$remaintodemand);
    }

    public function demandShareMoney($sls,$money)
    {
        //获取总收益
        $todaystr = date('Ymd',time());
        $this->load->model('redis_model');
        $redis = $this->redis_model->getRedisInstance();
        $redis->multi();
        $redis->get('slspostv2.scantotal.'.$sls);//海报总扫描数
        $redis->get('slsartv2.readtotal.'.$sls);//文章总阅读数
        $res = $redis->exec();
        $posttotalscan= $res[0]===false?0:(int)$res[0];
        $arttotalread = $res[1]===false?0:(int)$res[1];
        $totalMoney=($posttotalscan+$arttotalread)*10;//总收益（read*0.1*100）
        //获取已提现金额
        $totalDemandMoney=$this->getArticleTotalDemandMoney($sls);
        //获取剩余金额
        $remainMoney=$totalMoney-$totalDemandMoney;
        //剩余金额不能低于10元
        if ($remainMoney<1000) return array('status'=>2);
        //提现金额不能超过剩余金额
        if ($remainMoney<$money) return array('status'=>3);
        //提交提现申请
        //生成订单号
        $chars = "0123456789";
        $str = "";
        for ( $i = 0; $i < 6; $i++ )  {
            $str .= substr($chars, mt_rand(0, strlen($chars)-1), 1);
        }
        $tid = 'M'.date('YmdHis',time()).$str;

        $data=array('sls'=>$sls,'money'=>$money,'status'=>1,'created'=>time(),'tid'=>$tid);
        $id=$this->insertData('mod_salesman_money',$data);
        //获取剩余提现金额
        $remaintodemand=($remainMoney-$money)/100;
        return array('status'=>1,'remainmoney'=>$remaintodemand);
    }

    public function getMoneyRecord($sls)
    {
        $res=$this->db->select('*')->from('mod_salesman_money')
            ->where('sls =',$sls)->order_by('created','DESC')->get()->result_array();
        foreach ($res as &$row){
            $row['created']=date('Y-m-d H:i:s',$row['created']);
            $row['money']/=100;
            if ($row['status']==1){
                $row['status']='申请已提交，等待到账';
                $row['process']='';
            }elseif ($row['status']==2){
                $row['status']='提现成功，金额已到账';
                $row['process']=date('Y-m-d H:i:s',$row['process']);
            }else{
                $row['status']='申请状态异常';
                $row['created']='';
                $row['process']='';
            }
        }
        return $res;
    }
    public function getProductList($offset,$limit)
    {
        $data=$this->db->from('mod_salesman_goods')
            ->where(array('status'=>1))
            ->order_by('sort','ASC')
            ->limit($limit,$offset)
            ->get()->result_array();
        foreach ($data as &$row){
            $row['price']/=100;
            $row['priceUnderLine']/=100;
            $row['i_rate']/=100;
            $row['cover']="http://wap.nldou.com".$row['cover'];
        }
        $end = 0;
        $total = $this->db->where(array('status'=>1))->count_all_results('mod_salesman_goods');
        $listsize = $limit+$offset;
        if ($total<$listsize||$total==$listsize) $end=1;

        return array('list'=>$data,'end'=>$end);
    }
    public function getProductMedia($gid,$sls)
    {
        $img = $this->db->select('content')->from('mod_slsgood_media')
            ->where('gid =',$gid)->where('type = 1')->where('status = 1')
            ->order_by('sort','ASC')
            ->get()->result_array();
        $text = $this->db->select('content')->from('mod_slsgood_media')
            ->where('gid =',$gid)->where('type = 2')->where('status = 1')
            ->order_by('sort','ASC')
            ->get()->result_array();

        $info = $this->getProductByGid($gid);

        $link = $this->getProductShortUrl($gid,$sls);

        foreach($text as &$row){
            $row['content'].="<br/>购买链接：".$link;
            $row['copy']=str_replace("<br/>","\n",$row['content']);
        }

        $share = array(
            'link'=>"http://api.nldou.com/salesman/product/redirectKdt/".$sls."/".$gid,
            'title'=>$info['title'],
            'desc'=>"集玩乐与学习为一体的快乐教育神器，孩子玩不厌，家长玩不腻的魔法教具",
            'cover'=>"http://wap.nldou.com".$info['cover']
            );

        return array('img'=>$img,'text'=>$text,'share'=>$share);
    }
    public function getProductShortUrl($gid,$sls)
    {
        $this->load->model('redis_model');
        $redis=$this->redis_model->getRedisInstance();
        $link = $redis->get('slsgoodslink:'.$sls.':'.$gid);
        if ($link===false){
            $res = $this->db->select('link')->from('mod_salesman_goods')->where('id =',$gid)->get()->row_array();
            $orilink = $res['link'];
            //推广链接
            $link = "https://h5.youzan.com/v2/trade/directsellerJump/jump?kdt_id=18168297&sl=".$sls."&redirect_uri=";
            $link .= urlencode($orilink)."?sls=".$sls;
            //短链接
            $this->load->library("wxinterface/Wxinterface");
            $link = $this->wxinterface->longurl2short($link);
            if (isset($link['short_url'])){
                $redis->set('slsgoodslink:'.$sls.':'.$gid,$link['short_url']);
                return $link['short_url'];
            }else{return '';}
        }else{
            return $link;
        }
    }
    public function getProductByGid($gid)
    {
        return $this->db->from('mod_salesman_goods')->where('id =',$gid)->get()->row_array();
    }

    public function getShareRankList($offset,$limit,$time)
    {
        $this->load->model('redis_model');
        $redis=$this->redis_model->getRedisInstance();

        $start = $offset;
        $end = $offset+$limit-1;
        $today=date('Ymd',$time);
        $list = $redis->zRevRange('slssharerank.'.$today,$start,$end,true);
        $total = $redis->zCard('slssharerank.'.$today);

        $pullend=0;
        $listsize = $offset+$limit;
        if ($listsize>50||$listsize==50||$total<$listsize||$total==$listsize) $pullend=1;

        $todaystr = date('Y年m月d日',$time);
        $todaystr .= " 00:00~24:00";

        if (empty($list)) return array('list'=>array(),'end'=>$pullend,'time'=>$todaystr);

        $slsarr = array();
        $rankarr = array();
        $ranknum = $offset+1;
        foreach ($list as $sls=>$score){
            $rankarr[$sls]['rank']=$ranknum;
            $rankarr[$sls]['sls']=$sls;
            $rankarr[$sls]['share']=$score;
            $slsarr[] = $sls;
            $ranknum++;
        }

        $userdata = $this->db->select('u.userName as userName,u.userIcon as userIcon,s.idcode as sls')->from('mod_salesman as s')
            ->join('mod_user as u','u.uid=s.uid','left')
            ->where_in('s.idcode',$slsarr)->get()->result_array();
        foreach ($userdata as $u){
            $rankarr[$u['sls']]['userName']=$u['userName'];
            $rankarr[$u['sls']]['userIcon']=strrpos($u['userIcon'],'http://')===false?"http://wap.nldou.com".$u['userIcon']:$u['userIcon'];
        }

        return array('list'=>array_values($rankarr),'end'=>$pullend,'time'=>$todaystr);
    }

    public function getShareArticleVistor($sls,$limit,$offset)
    {
        //时间范围为当天
        $todaystr = date('Y-m-d',time());
        $start = strtotime($todaystr)-24*6*3600;
        $stop = strtotime($todaystr)+24*3600;

        $data=$this->db->select('u.userName,u.userIcon,a.title,s.time')
            ->from('mod_slsarticle_stat as s')
            ->join('mod_salesman_article as a','a.model=s.model','left')
            ->join('mod_user as u','u.uid=s.uid','left')
            ->where('s.time >',$start)
            ->where('s.time <',$stop)
            ->where('s.sls =',$sls)
            ->order_by('s.time','DESC')
            ->limit($limit,$offset)
            ->get()->result_array();
        foreach ($data as &$row){
            $row['userIcon']=strpos($row['userIcon'],'http')===0?$row['userIcon']:'http://wap.nldou.com'.$row['userIcon'];
            $row['time']=date('Y-m-d H:i:s',$row['time']);
        }

        $end = 0;
        $this->db->where(array('time >'=>$start,'time <'=>$stop,'sls ='=>$sls));
        $this->db->from('mod_slsarticle_stat');
        $total=$this->db->count_all_results();
        $listsize = $limit+$offset;
        if ($total<$listsize||$total==$listsize) $end=1;

        return array('list'=>$data,'end'=>$end,'listsize'=>$listsize);
    }

    public function getSharePostScanner($sls,$limit,$offset)
    {
        //时间范围为当天
        $todaystr = date('Y-m-d',time());
        $start = strtotime($todaystr)-24*6*3600;
        $stop = strtotime($todaystr)+24*3600;

        $data=$this->db->select('u.userName,u.userIcon,p.url,s.time')
            ->from('mod_slspost_stat as s')
            ->join('mod_salesman_post_v2 as p','p.id=s.postid','left')
            ->join('mod_user as u','u.uid=s.uid','left')
            ->where('s.time >',$start)
            ->where('s.time <',$stop)
            ->where('s.sls =',$sls)
            ->order_by('s.time','DESC')
            ->limit($limit,$offset)
            ->get()->result_array();
        foreach ($data as &$row){
            $row['userIcon']=strpos($row['userIcon'],'http')===0?$row['userIcon']:'http://wap.nldou.com'.$row['userIcon'];
            $row['time']=date('Y-m-d H:i:s',$row['time']);
            $row['url']='http://wap.nldou.com'.$row['url'];
        }

        $end = 0;
        $this->db->where(array('time >'=>$start,'time <'=>$stop,'sls ='=>$sls));
        $this->db->from('mod_slspost_stat');
        $total=$this->db->count_all_results();
        $listsize = $limit+$offset;
        if ($total<$listsize||$total==$listsize) $end=1;

        return array('list'=>$data,'end'=>$end);
    }
}